SlideShare a Scribd company logo
1 of 59
HTML / CSS / JS
Best practices and optimization techniques
Fi (Fantasy Interactive)




     www.f-i.com       david.lindkvist@f-i.com


                                             2
Why are we here?
 The web is slowly moving towards using open standards
   HTML, CSS and Javascript is the new Flash (Silverlight anyone?)


 Javascript performance has doubled in the past few years

 More and more application logic end up in the UI

 HTML, CSS and JS are VERY forgiving - we need solid
 conventions to build on



                                                            3
Agenda
 HTML

 CSS

 Javascript & jQuery

 Performance optimizations

 Visual optimizations



                             4
Semantic Markup
 Use correct tag to describe your content

 H1, H2, H3 tags for headings
 OL, UL, DL for ordered, unordered, and definition lists
 P tags for paragraphs

 Pages immediately become more accessible, both for
 search engines, and humans alike (such as a user who
 need to use a screen reader)



                                                      5
Semantic Markup - naming
 header, topNavigation, sidebarNavigation, leftColumn,
 rightColumn, footer... sounds familiar?

 Avoid using names that describe position... think
 content!

 brandingArea, mainNavigation, subNavigation,
 mainContent, sub content, siteInfo

 CSS can change position of your content!


                                                     6
Keep it clean!
 Try not to bloat your markup with unnecessary
 elements or CSS classes.

 Avoid using extra block elements just for positioning -
 change to display:block on inline elements instead.

 Use the cascading functionality in CSS instead of
 adding unnecessary classes




                                                       7
A case of div-itis
<div class="content">
  <p>
     Lorem ipsum dolor sit amet dolor adispiscing elit.
  </p>
</div>
<div class="featureList">
  <ul>
     <li class="redBullet">Dog</li>
     <li class="redBullet">Cat</li>
     <li class="redBullet">Mouse</li>
  </ul>
</div>

                                                          8
A case of class-itis
<p class="content" >
  Lorem ipsum dolor sit amet dolor adispiscing elit.
</p>
<ul class="featureList" >
  <li class="redBullet">Dog</li>
  <li class="redBullet">Cat</li>
  <li class="redBullet">Mouse</li>
</ul>




                                                       9
Clean and simple markup!
<p>
  Lorem ipsum dolor sit amet dolor adispiscing elit.
</p>
<ul class="redBullets" >
  <li>Dog</li>
  <li>Cat</li>
  <li>Mouse</li>
</ul>




                                                       10
CSS - Words of advice
 Aim for readable, maintainable code (leave the
 complex shorthand to the CSS compression
 algorithms)
 Use the cascade! That’s what it’s there for.
 Be mindful of CSS selectors
   pseudo-classes and properties which aren’t available to all
   browsers (IE6 is going to be your enemy most of the time)
 Class names should NOT BE CHAINED.
   IE6 does not support this: “div.classnameA.classnameB {”
 Check changes in all browsers as you make the
 changes — not once you’re 90% “done”

                                                                 11
CSS - The Cascade
 Sorts by origin and importance
    1. inline style -> 2. embedded stylesheet -> 3. linked stylesheet
    A style rule with higher importance wins over identical rules
    with lower importance
 Sorts by specificity of the CSS selector

 Notes:
    If 2 or more rules have the same importance, origin and
    specificity, the last one wins
    The browsers default style sheet is treated as if it’s an
    imported stylesheet imported before all other



                                                                12
Use a reset stylesheet
 All browsers have a default stylesheet

 Resets default view behaviors of many HTML elements
 to display uniformly across all browsers

 Include as first external stylesheet

 Example: Popular reset stylesheets
    Eric Meyer’s reset.css
    YUI reset.css


                                                 13
CSS - File structure
 Choose a file structure that makes sense for your
 project!

 Some larger projects benefits from a more separated
 approach:
   reset.css
   typography.css
   layout.css
   gui.css


 Other projects may be fine using one single stylesheet

                                                     14
CSS - ID your body
 Flexibility to apply page specific styles without adding
 separate stylesheets

 </head>
 <body id=”contactPage”>

 Override default style using the body ID:

 a { color: blue; }

 #contactPage a { color: red; }


                                                       15
CSS - Sliding Doors
 Create dynamic length graphics for buttons, tabs and
 menu items

 Use 2 nested elements and slide background images
 over each other

          <a href=”#”><span>Text</span></a>

        <span>                                <a>
        left
        side
                          Text                right
                                              side



                                                      16
CSS image sprites
 Contain several different graphics in one file

 WHY?
    Reduces number of HTTP calls to server
    No “flicker” when first rolling over item with hover state.
       Modifying CSS background-position is instant!



 Example: button sprites




                                                                  17
Tips when using image sprites
 Expect sprites to grow—group/space items accordingly

 Place sprites on even multiples (50px, 100px, 500px)

 Avoid using string values for positioning (ie, “top”, “left”,
 “right”, etc.). Pixels are preferred when specifying the
 background position for all sprites
    Except in the case of the sliding-doors technique. Here, a
    value of 100% is necessary.




                                                                 18
Tips when using image sprites
 If using the ‘background: ...’ CSS shorthand, enter ALL
 values in their PROPER order:
   1. background-color: transparent | color
   2. background-image: none | url(path/to/image.jpg)
   3. background-repeat: no-repeat | repeat | repeat-x | repeat-y
   4. background-attachment: scroll | fixed
   5. background-position: 0px 0px


 Example:
   background: transparent url(../assets/sprite_main.png) no-
   repeat scroll 0px -50px;



                                                                19
Tips when using image sprites
 Keep PSDs of the sprites up-to-date

 Remember that global light settings get reset to the
 default of 120°— double check the drop shadows with
 the original design, most designers prefer to use 90°!!!

 GIFs and PNGs optimize horizontally

 Experiment with compression settings. Often times,
 PNG-8 will be smaller.


                                                      20
PNG optimization
 PNG was developed as an open-source replacement
 for GIF

 Introduced new features for compression

 Photoshop don’t offer any optimization options
   PNG-24 Truecolor
   PNG-8 Indexed-color


 PNG’s are not “unoptimizable”!


                                                  21
GIF compression
 Each number represents a unique color
 GIF compress horizontally, thus an image like this will
 not compress well:




                                                      22
PNG Scanline filtering (delta filters)
 2 represents applied filter “UP”
 “For the current pixel take the value of the above pixel
 and add it to the current value.”




                                                       23
PNG Scanline filtering (delta filters)
 1 represents applied filter “SUB”
 “Take the value of the left pixel and add it to the current
 value.”




                                                        24
PNG Scanline filtering (delta filters)
 1 represents applied filter “SUB”
 “Take the value of the left pixel and add it to the current
 value.”




                                                        25
PNG optimization
 Compression utilities can help us:
   Pick up best image type (truecolor, indexed-color)
   Pick up best delta filters (5 delta filters to select from)
   Pick up best compression strategy


 All these operations does NOT affect image quality!

 One of the best compression services:
   http://www.gracepointafterfive.com/punypng
   But where is the command line script?



                                                                 26
Progressive Enhancement
 The web was using Graceful Degradation
   Target most advanced browsers, apply fixes to older browsers


 Moving towards Progressive Enhancement
   Focus on the content!
      1. Begin with semantic markup
      2. Apply basic style using CSS
      3. Transform into richer user experience using JS and CSS

   Examples:
      Atari.com
      Alkoholprofilen.se


                                                                  27
Javascript namespaces
 Stay away from the global namespace to avoid
 collisions with 3rd party code

 Wrap all functions in a namespace object:

 var myNamespace = {};
 myNamespace.myFunction = function () {
    // I’m not a global function and I like it
 };

 Example: Atari.com global.js

                                                 28
jQuery - Sizzle selectors
 jQuery includes the Sizzle CSS selector engine from
 version 1.3

 The syntax goes something like this:
   $(String selector, DOMElement context);


 Example:
   var myList = $(‘#myList’);
   $(‘li’, myList);


 Supports CSS3 selectors

                                                   29
jQuery - Chain selectors
 Requires 3 DOM traversals:
        $(‘#mydiv’).html(‘Hello World!’);
        $(‘#mydiv’).css(‘border’, ‘1px solid black’);
        $(‘#mydiv’).fadeIn(‘fast’);


 Requires 1 DOM traversal:
        $(‘#mydiv’).html(‘Hello World!’).css(‘color’, ‘red’).fadeIn(‘fast’);
   OR
        var myDiv = $(‘#mydiv’);
        myDiv.html(‘Hello World!’);
        myDiv.css(‘color’, ‘red’);
        myDiv.fadeIn(‘fast’);



                                                                               30
jQuery - Chain selectors
 Not visually stunning! But...
 ... cuts down on DOM traversal and hundreds of
 internal calls:
   $(‘#mydiv’)
      .html(‘Hello World!’)
      .children(‘p’)
         .css(‘color’, ‘red’)
         .end()
      .css(‘background-color’, ‘#ffdead’);

   This chain will dip into its children, and the end() method will
   end the chain, reverting to the initial selector



                                                                 31
jQuery - Plugin Pattern
 jQuery offers a mechanism to extend it with plugins

 Most internal methods and functions are written using
 this pattern

 Helps us build reusable components

 Should be easy to override default properties




                                                       32
jQuery - Plugin Pattern
 All new methods are attached to the jQuery.fn object,
 all functions to the jQuery object.
 inside methods, 'this' is a reference to the current
 jQuery object.
 Any methods or functions you attach must have a
 semicolon (;) at the end or compressed code will break
 Your method must return the jQuery object
 You should use this.each to iterate over the current set
 of matched elements
 Always attach the plugin to jQuery directly instead of $,
 so users can use a custom alias via noConflict().

                                                       33
Example plugin pattern
 Template example: The Fi plugin pattern

 Real world example: The Fi checkbox plugin




                                              34
Page specific Javascript
 Inline script
    Dynamic config vars that may change for each page load
 External scripts
    page-specific javascript file
       Used to load plugins
       Override plugin defaults with config variables




 EXAMPLE: load and configure labelinput plugin



                                                             35
Qunit
 Latest version does not rely on jQuery

 Example: checkbox plugin unit test

 Testswarm.com




                                          36
JS logging
 alert()

 console.log()

 Blackbird JS
    http://www.gscottolson.com/blackbirdjs/


 Example: Creating an abstract jQuery log function to
 wrap any logger utility.



                                                    37
Optimize page load
 Use external resources not inline JS/CSS
   External files will be cached and minimizes document size


 CSS at the top

 JS at the bottom




                                                               38
Javascript files always block!
 Blocks render because they might document.write()

 Downloads sequentially




                                                     39
Skip document.ready()
 Will only fire once all external resources has been
 loaded.
    External scripts from third parties like Google Analytics cause
    long delays (~1s) before event fires


 Put script in correct order at bottom of page

 Put analytics code last!

 WARNING! Requires a solid file structure


                                                                40
Example - Load order
   <head>
      reset.css
      layout.css
   </head>
   <body>
      <!-- document markup -->
      jquery.js
      jquery.checkbox.js
      global.js
      page-home.js
      google-analytics.js
   </body>



                                 41
Optimize load time
 Compress external resources!

 CSS compressor (YUICompressor, CSSTidy)

 JS compressor (JSmin, YUICompressor, etc)

 GZIP server response

 Example: YUICompressor and GZIP size comparisons



                                              42
JSLint Your Code
 What’s JSLint?
   Looks for problems in Javascript code
   It’s a code quality tool
   A Javascript syntax checker and validator


 Prevents errors occurring from compressing files!
   Looks at style conventions and structural problems that may
   cause problems


 WARNING: JSLint will hurt your feelings!



                                                            43
JSLint Recommended options
 1. In the “Options” box, click “The Good Parts”
 2. Uncheck “Allow one var statement per function”
 3. Check “Assume a browser”
 4. Uncheck “Disallow ++ and --”
 5. Uncheck “Require ‘use strict;’” (ECMAScript 5 strict
 mode) unless you actually test in a strict browser

 http://www.jslint.com

 EXAMPLE: JSlint Checbox plugin

                                                      44
Reduce number of HTTP requests
 Biggest impact on end-user response times is the
 number of page components

 With an empty cache, each external component
 requires a new HTTP request

 Can’t the browser download all files in parallel?

 HTML/1.1 spec. suggests max 2 simultaneous
 downloads per hostname


                                                     45
How do we reduce number of
HTTP requests?
 Merge common files
   Global Javascript files
   Global stylesheets


 Use CSS image sprites!




                             46
Automated build script
 Let the ANT do the work! (or any other build tool)

 1. merge common files

 2. compress merged files

 EXAMPLE: Ant build script




                                                      47
Maximize parallel downloads
 Most browsers only download 2 files from same
 domain in parallel

 2-4 domains give optimal performance

 Remember: Javascripts are usually downloaded and
 parsed sequentially

 EXAMPLE: Panamera Family Tree - 1 vs 4 domains



                                                  48
Maximize parallel downloads
 Downloading 2 components in parallel using 1
 hostname




                                                49
Maximize parallel downloads
 Downloading 8 components in parallel using 4
 hostnames




                                                50
Yahoo! performance tests




                           51
Maximize parallel downloads
 Yahoo! performance guidelines:
   Use at least 2 hostnames
   Use no more than 4 hostnames
   Reduce number of components in page


 2-4 domains give optimal performance - test!

 Remember: Javascripts are usually downloaded and
 parsed sequentially

 EXAMPLE: Panamera Family Tree - 1 vs 4 domains

                                                  52
Visual optimizations
 Progressive Enhancement + scripts at bottom can
 cause load flickering

   Example: Throttle checkbox plugin


 How do we prevent this?

   Hide using CSS until Javascript shows the enhanced
   component?

   Example: Test checkbox using disabled Javascript


                                                        53
Visual optimizations
 Break the rules!

 Let’s hide enhanced components in HEAD using
 Javascript.

   Load external stylesheet hideOnLoad.css using
   document.write()

   <script>
      document.write(‘<link href=”...”></link>’);
   </script>



                                                    54
Cache busting
 Add version numbers on external resources:
   Stylesheets
   Javascript files
   CSS sprites
   Images


 Example:

   <script src=”jquery.fi.checkbox.js?v=1.0” type=”...”></script>




                                                                55
Firefox Plugins
 Firebug plugin & Firebug lite
 Web Developer toolbar
 HTML Validator
 YSlow
 Page Speed
 PixelPerfect
    Example: atari.com
 SenSEO
    Example: panamera.com
    500k visitors since Sep10. SEO is generating 10% of visitors -
    most popular path after user typing in URL

                                                               56
Tools
 Charles http proxy
   Bandwidth throttling
   Excellent request/response sniffing
      Record sessions
      Can parse binary AMF messages (Action Message Format) used
      by Adobe Flash


 Speed Tracer for Chrome

 IDE: Aptana Studio
   Based on Eclipse.
   Good support for JS frameworks!

                                                             57
Further reading
 Yahoo Performance
   http://developer.yahoo.com/performance/


 A List Apart - http://alistapart.com
 Sitepoint - http://sitepoint.com
 Smashing Magazine - http://smashingmagazine.com
 Ajaxian - http://ajaxian.com/

 John Resig’s Blog - http://ejohn.com
 Steve Souder’s Blog - http://stevesouders.com

                                                 58
Thanks!




 C


     Contact: david.lindkvist@f-i.com   www.f-i.com



                                                      59

More Related Content

What's hot

HTML, CSS And JAVASCRIPT!
HTML, CSS And JAVASCRIPT!HTML, CSS And JAVASCRIPT!
HTML, CSS And JAVASCRIPT!Syahmi RH
 
(Fast) Introduction to HTML & CSS
(Fast) Introduction to HTML & CSS (Fast) Introduction to HTML & CSS
(Fast) Introduction to HTML & CSS Dave Kelly
 
Front-end development introduction (HTML, CSS). Part 1
Front-end development introduction (HTML, CSS). Part 1Front-end development introduction (HTML, CSS). Part 1
Front-end development introduction (HTML, CSS). Part 1Oleksii Prohonnyi
 
Introduction to Javascript
Introduction to JavascriptIntroduction to Javascript
Introduction to JavascriptAmit Tyagi
 
An Overview of HTML, CSS & Java Script
An Overview of HTML, CSS & Java ScriptAn Overview of HTML, CSS & Java Script
An Overview of HTML, CSS & Java ScriptFahim Abdullah
 
Event In JavaScript
Event In JavaScriptEvent In JavaScript
Event In JavaScriptShahDhruv21
 
Introduction to CSS3
Introduction to CSS3Introduction to CSS3
Introduction to CSS3Doris Chen
 
Complete Lecture on Css presentation
Complete Lecture on Css presentation Complete Lecture on Css presentation
Complete Lecture on Css presentation Salman Memon
 
Html / CSS Presentation
Html / CSS PresentationHtml / CSS Presentation
Html / CSS PresentationShawn Calvert
 
Intro to HTML and CSS basics
Intro to HTML and CSS basicsIntro to HTML and CSS basics
Intro to HTML and CSS basicsEliran Eliassy
 
Presentation of bootstrap
Presentation of bootstrapPresentation of bootstrap
Presentation of bootstrap1amitgupta
 
Introduction to HTML and CSS
Introduction to HTML and CSSIntroduction to HTML and CSS
Introduction to HTML and CSSMario Hernandez
 

What's hot (20)

HTML, CSS And JAVASCRIPT!
HTML, CSS And JAVASCRIPT!HTML, CSS And JAVASCRIPT!
HTML, CSS And JAVASCRIPT!
 
Java script
Java scriptJava script
Java script
 
Java Script ppt
Java Script pptJava Script ppt
Java Script ppt
 
(Fast) Introduction to HTML & CSS
(Fast) Introduction to HTML & CSS (Fast) Introduction to HTML & CSS
(Fast) Introduction to HTML & CSS
 
Front-end development introduction (HTML, CSS). Part 1
Front-end development introduction (HTML, CSS). Part 1Front-end development introduction (HTML, CSS). Part 1
Front-end development introduction (HTML, CSS). Part 1
 
Introduction to Javascript
Introduction to JavascriptIntroduction to Javascript
Introduction to Javascript
 
An Overview of HTML, CSS & Java Script
An Overview of HTML, CSS & Java ScriptAn Overview of HTML, CSS & Java Script
An Overview of HTML, CSS & Java Script
 
Javascript
JavascriptJavascript
Javascript
 
Html presentation
Html presentationHtml presentation
Html presentation
 
Event In JavaScript
Event In JavaScriptEvent In JavaScript
Event In JavaScript
 
Bootstrap
BootstrapBootstrap
Bootstrap
 
Introduction to CSS3
Introduction to CSS3Introduction to CSS3
Introduction to CSS3
 
Complete Lecture on Css presentation
Complete Lecture on Css presentation Complete Lecture on Css presentation
Complete Lecture on Css presentation
 
Dom
Dom Dom
Dom
 
Html / CSS Presentation
Html / CSS PresentationHtml / CSS Presentation
Html / CSS Presentation
 
Intro to HTML and CSS basics
Intro to HTML and CSS basicsIntro to HTML and CSS basics
Intro to HTML and CSS basics
 
Basics of JavaScript
Basics of JavaScriptBasics of JavaScript
Basics of JavaScript
 
Presentation of bootstrap
Presentation of bootstrapPresentation of bootstrap
Presentation of bootstrap
 
Web Development using HTML & CSS
Web Development using HTML & CSSWeb Development using HTML & CSS
Web Development using HTML & CSS
 
Introduction to HTML and CSS
Introduction to HTML and CSSIntroduction to HTML and CSS
Introduction to HTML and CSS
 

Viewers also liked

HTML5 Bootcamp: Essential HTML, CSS, & JavaScript
HTML5 Bootcamp: Essential HTML, CSS, & JavaScriptHTML5 Bootcamp: Essential HTML, CSS, & JavaScript
HTML5 Bootcamp: Essential HTML, CSS, & JavaScriptTodd Anglin
 
JavaScript - An Introduction
JavaScript - An IntroductionJavaScript - An Introduction
JavaScript - An IntroductionManvendra Singh
 
HTML CSS JavaScript jQuery Training
HTML CSS JavaScript jQuery TrainingHTML CSS JavaScript jQuery Training
HTML CSS JavaScript jQuery Trainingubshreenath
 
An Seo’s Intro to Web Dev, HTML, CSS and JavaScript
An Seo’s Intro to Web Dev, HTML, CSS and JavaScriptAn Seo’s Intro to Web Dev, HTML, CSS and JavaScript
An Seo’s Intro to Web Dev, HTML, CSS and JavaScriptTroyfawkes
 
Modular HTML, CSS, & JS Workshop
Modular HTML, CSS, & JS WorkshopModular HTML, CSS, & JS Workshop
Modular HTML, CSS, & JS WorkshopShay Howe
 
Introduction to CSS
Introduction to CSSIntroduction to CSS
Introduction to CSSAmit Tyagi
 
HTML, CSS and Java Scripts Basics
HTML, CSS and Java Scripts BasicsHTML, CSS and Java Scripts Basics
HTML, CSS and Java Scripts BasicsSun Technlogies
 
8th Computer Jeopardy Game
8th   Computer Jeopardy Game8th   Computer Jeopardy Game
8th Computer Jeopardy Gameguestbbe861f
 
Mobile development in age of Internet of Things and programming Apple Watch
Mobile development in age of Internet of Things and programming Apple WatchMobile development in age of Internet of Things and programming Apple Watch
Mobile development in age of Internet of Things and programming Apple WatchJanusz Chudzynski
 
Internet of things, and rise of ibeacons
Internet of things, and rise of ibeaconsInternet of things, and rise of ibeacons
Internet of things, and rise of ibeaconsJanusz Chudzynski
 
Paper Presentation: Data Mining User Preference in Interactive Multimedia
Paper Presentation: Data Mining User Preference in Interactive MultimediaPaper Presentation: Data Mining User Preference in Interactive Multimedia
Paper Presentation: Data Mining User Preference in Interactive MultimediaJeanette Howe
 
Lotus - normas gráficas
Lotus - normas gráficasLotus - normas gráficas
Lotus - normas gráficasTT TY
 
OOCSS, SMACSS or BEM?
OOCSS, SMACSS or BEM?OOCSS, SMACSS or BEM?
OOCSS, SMACSS or BEM?Michael Posso
 

Viewers also liked (20)

Html JavaScript and CSS
Html JavaScript and CSSHtml JavaScript and CSS
Html JavaScript and CSS
 
reveal.js 3.0.0
reveal.js 3.0.0reveal.js 3.0.0
reveal.js 3.0.0
 
HTML5 Bootcamp: Essential HTML, CSS, & JavaScript
HTML5 Bootcamp: Essential HTML, CSS, & JavaScriptHTML5 Bootcamp: Essential HTML, CSS, & JavaScript
HTML5 Bootcamp: Essential HTML, CSS, & JavaScript
 
JavaScript - An Introduction
JavaScript - An IntroductionJavaScript - An Introduction
JavaScript - An Introduction
 
HTML CSS JavaScript jQuery Training
HTML CSS JavaScript jQuery TrainingHTML CSS JavaScript jQuery Training
HTML CSS JavaScript jQuery Training
 
An Seo’s Intro to Web Dev, HTML, CSS and JavaScript
An Seo’s Intro to Web Dev, HTML, CSS and JavaScriptAn Seo’s Intro to Web Dev, HTML, CSS and JavaScript
An Seo’s Intro to Web Dev, HTML, CSS and JavaScript
 
Modular HTML, CSS, & JS Workshop
Modular HTML, CSS, & JS WorkshopModular HTML, CSS, & JS Workshop
Modular HTML, CSS, & JS Workshop
 
Introduction to HTML and CSS
Introduction to HTML and CSSIntroduction to HTML and CSS
Introduction to HTML and CSS
 
Javascript
JavascriptJavascript
Javascript
 
Introduction to CSS
Introduction to CSSIntroduction to CSS
Introduction to CSS
 
Javascript
JavascriptJavascript
Javascript
 
HTML, CSS and Java Scripts Basics
HTML, CSS and Java Scripts BasicsHTML, CSS and Java Scripts Basics
HTML, CSS and Java Scripts Basics
 
Html Ppt
Html PptHtml Ppt
Html Ppt
 
Php Presentation
Php PresentationPhp Presentation
Php Presentation
 
8th Computer Jeopardy Game
8th   Computer Jeopardy Game8th   Computer Jeopardy Game
8th Computer Jeopardy Game
 
Mobile development in age of Internet of Things and programming Apple Watch
Mobile development in age of Internet of Things and programming Apple WatchMobile development in age of Internet of Things and programming Apple Watch
Mobile development in age of Internet of Things and programming Apple Watch
 
Internet of things, and rise of ibeacons
Internet of things, and rise of ibeaconsInternet of things, and rise of ibeacons
Internet of things, and rise of ibeacons
 
Paper Presentation: Data Mining User Preference in Interactive Multimedia
Paper Presentation: Data Mining User Preference in Interactive MultimediaPaper Presentation: Data Mining User Preference in Interactive Multimedia
Paper Presentation: Data Mining User Preference in Interactive Multimedia
 
Lotus - normas gráficas
Lotus - normas gráficasLotus - normas gráficas
Lotus - normas gráficas
 
OOCSS, SMACSS or BEM?
OOCSS, SMACSS or BEM?OOCSS, SMACSS or BEM?
OOCSS, SMACSS or BEM?
 

Similar to HTML CSS & Javascript

Adobe MAX 2008: HTML/CSS + Fireworks
Adobe MAX 2008: HTML/CSS + FireworksAdobe MAX 2008: HTML/CSS + Fireworks
Adobe MAX 2008: HTML/CSS + FireworksNathan Smith
 
An Introduction to CSS Frameworks
An Introduction to CSS FrameworksAn Introduction to CSS Frameworks
An Introduction to CSS FrameworksAdrian Westlake
 
Girl Develop It Cincinnati: Intro to HTML/CSS Class 4
Girl Develop It Cincinnati: Intro to HTML/CSS Class 4Girl Develop It Cincinnati: Intro to HTML/CSS Class 4
Girl Develop It Cincinnati: Intro to HTML/CSS Class 4Erin M. Kidwell
 
Responsive Web Design: Clever Tips and Techniques
Responsive Web Design: Clever Tips and TechniquesResponsive Web Design: Clever Tips and Techniques
Responsive Web Design: Clever Tips and TechniquesVitaly Friedman
 
CSS Methodology
CSS MethodologyCSS Methodology
CSS MethodologyZohar Arad
 
Organize Your Website With Advanced CSS Tricks
Organize Your Website With Advanced CSS TricksOrganize Your Website With Advanced CSS Tricks
Organize Your Website With Advanced CSS TricksAndolasoft Inc
 
Structuring your CSS for maintainability: rules and guile lines to write CSS
Structuring your CSS for maintainability: rules and guile lines to write CSSStructuring your CSS for maintainability: rules and guile lines to write CSS
Structuring your CSS for maintainability: rules and guile lines to write CSSSanjoy Kr. Paul
 
Client side performance compromises worth making
Client side performance compromises worth makingClient side performance compromises worth making
Client side performance compromises worth makingCathy Lill
 
Responsive Web Design tips and tricks.
Responsive Web Design tips and tricks.Responsive Web Design tips and tricks.
Responsive Web Design tips and tricks.GaziAhsan
 
Html 5 mobile - nitty gritty
Html 5 mobile - nitty grittyHtml 5 mobile - nitty gritty
Html 5 mobile - nitty grittyMario Noble
 
Sass Essentials at Mobile Camp LA
Sass Essentials at Mobile Camp LASass Essentials at Mobile Camp LA
Sass Essentials at Mobile Camp LAJake Johnson
 
Practical tipsmakemobilefaster oscon2016
Practical tipsmakemobilefaster oscon2016Practical tipsmakemobilefaster oscon2016
Practical tipsmakemobilefaster oscon2016Doris Chen
 
"Responsive Web Design: Clever Tips and Techniques". Vitaly Friedman, Smashin...
"Responsive Web Design: Clever Tips and Techniques". Vitaly Friedman, Smashin..."Responsive Web Design: Clever Tips and Techniques". Vitaly Friedman, Smashin...
"Responsive Web Design: Clever Tips and Techniques". Vitaly Friedman, Smashin...Yandex
 
Spectrum 2015 going online with style - an intro to css
Spectrum 2015   going online with style - an intro to cssSpectrum 2015   going online with style - an intro to css
Spectrum 2015 going online with style - an intro to cssNeil Perlin
 
The Need for Speed - SMX Sydney 2013
The Need for Speed - SMX Sydney 2013The Need for Speed - SMX Sydney 2013
The Need for Speed - SMX Sydney 2013Bastian Grimm
 
10 Tips to make your Website lightning-fast - SMX Stockholm 2012
10 Tips to make your Website lightning-fast - SMX Stockholm 201210 Tips to make your Website lightning-fast - SMX Stockholm 2012
10 Tips to make your Website lightning-fast - SMX Stockholm 2012Bastian Grimm
 

Similar to HTML CSS & Javascript (20)

Adobe MAX 2008: HTML/CSS + Fireworks
Adobe MAX 2008: HTML/CSS + FireworksAdobe MAX 2008: HTML/CSS + Fireworks
Adobe MAX 2008: HTML/CSS + Fireworks
 
An Introduction to CSS Frameworks
An Introduction to CSS FrameworksAn Introduction to CSS Frameworks
An Introduction to CSS Frameworks
 
Girl Develop It Cincinnati: Intro to HTML/CSS Class 4
Girl Develop It Cincinnati: Intro to HTML/CSS Class 4Girl Develop It Cincinnati: Intro to HTML/CSS Class 4
Girl Develop It Cincinnati: Intro to HTML/CSS Class 4
 
Responsive Web Design: Clever Tips and Techniques
Responsive Web Design: Clever Tips and TechniquesResponsive Web Design: Clever Tips and Techniques
Responsive Web Design: Clever Tips and Techniques
 
CSS Methodology
CSS MethodologyCSS Methodology
CSS Methodology
 
Organize Your Website With Advanced CSS Tricks
Organize Your Website With Advanced CSS TricksOrganize Your Website With Advanced CSS Tricks
Organize Your Website With Advanced CSS Tricks
 
Team styles
Team stylesTeam styles
Team styles
 
Pfnp slides
Pfnp slidesPfnp slides
Pfnp slides
 
Structuring your CSS for maintainability: rules and guile lines to write CSS
Structuring your CSS for maintainability: rules and guile lines to write CSSStructuring your CSS for maintainability: rules and guile lines to write CSS
Structuring your CSS for maintainability: rules and guile lines to write CSS
 
Client side performance compromises worth making
Client side performance compromises worth makingClient side performance compromises worth making
Client side performance compromises worth making
 
Responsive Web Design tips and tricks.
Responsive Web Design tips and tricks.Responsive Web Design tips and tricks.
Responsive Web Design tips and tricks.
 
Rwd slidedeck
Rwd slidedeckRwd slidedeck
Rwd slidedeck
 
Html 5 mobile - nitty gritty
Html 5 mobile - nitty grittyHtml 5 mobile - nitty gritty
Html 5 mobile - nitty gritty
 
Sass Essentials at Mobile Camp LA
Sass Essentials at Mobile Camp LASass Essentials at Mobile Camp LA
Sass Essentials at Mobile Camp LA
 
Practical tipsmakemobilefaster oscon2016
Practical tipsmakemobilefaster oscon2016Practical tipsmakemobilefaster oscon2016
Practical tipsmakemobilefaster oscon2016
 
"Responsive Web Design: Clever Tips and Techniques". Vitaly Friedman, Smashin...
"Responsive Web Design: Clever Tips and Techniques". Vitaly Friedman, Smashin..."Responsive Web Design: Clever Tips and Techniques". Vitaly Friedman, Smashin...
"Responsive Web Design: Clever Tips and Techniques". Vitaly Friedman, Smashin...
 
Css
CssCss
Css
 
Spectrum 2015 going online with style - an intro to css
Spectrum 2015   going online with style - an intro to cssSpectrum 2015   going online with style - an intro to css
Spectrum 2015 going online with style - an intro to css
 
The Need for Speed - SMX Sydney 2013
The Need for Speed - SMX Sydney 2013The Need for Speed - SMX Sydney 2013
The Need for Speed - SMX Sydney 2013
 
10 Tips to make your Website lightning-fast - SMX Stockholm 2012
10 Tips to make your Website lightning-fast - SMX Stockholm 201210 Tips to make your Website lightning-fast - SMX Stockholm 2012
10 Tips to make your Website lightning-fast - SMX Stockholm 2012
 

Recently uploaded

Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?Antenna Manufacturer Coco
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CVKhem
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEarley Information Science
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUK Journal
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 

Recently uploaded (20)

Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 

HTML CSS & Javascript

  • 1. HTML / CSS / JS Best practices and optimization techniques
  • 2. Fi (Fantasy Interactive) www.f-i.com david.lindkvist@f-i.com 2
  • 3. Why are we here? The web is slowly moving towards using open standards HTML, CSS and Javascript is the new Flash (Silverlight anyone?) Javascript performance has doubled in the past few years More and more application logic end up in the UI HTML, CSS and JS are VERY forgiving - we need solid conventions to build on 3
  • 4. Agenda HTML CSS Javascript & jQuery Performance optimizations Visual optimizations 4
  • 5. Semantic Markup Use correct tag to describe your content H1, H2, H3 tags for headings OL, UL, DL for ordered, unordered, and definition lists P tags for paragraphs Pages immediately become more accessible, both for search engines, and humans alike (such as a user who need to use a screen reader) 5
  • 6. Semantic Markup - naming header, topNavigation, sidebarNavigation, leftColumn, rightColumn, footer... sounds familiar? Avoid using names that describe position... think content! brandingArea, mainNavigation, subNavigation, mainContent, sub content, siteInfo CSS can change position of your content! 6
  • 7. Keep it clean! Try not to bloat your markup with unnecessary elements or CSS classes. Avoid using extra block elements just for positioning - change to display:block on inline elements instead. Use the cascading functionality in CSS instead of adding unnecessary classes 7
  • 8. A case of div-itis <div class="content"> <p> Lorem ipsum dolor sit amet dolor adispiscing elit. </p> </div> <div class="featureList"> <ul> <li class="redBullet">Dog</li> <li class="redBullet">Cat</li> <li class="redBullet">Mouse</li> </ul> </div> 8
  • 9. A case of class-itis <p class="content" > Lorem ipsum dolor sit amet dolor adispiscing elit. </p> <ul class="featureList" > <li class="redBullet">Dog</li> <li class="redBullet">Cat</li> <li class="redBullet">Mouse</li> </ul> 9
  • 10. Clean and simple markup! <p> Lorem ipsum dolor sit amet dolor adispiscing elit. </p> <ul class="redBullets" > <li>Dog</li> <li>Cat</li> <li>Mouse</li> </ul> 10
  • 11. CSS - Words of advice Aim for readable, maintainable code (leave the complex shorthand to the CSS compression algorithms) Use the cascade! That’s what it’s there for. Be mindful of CSS selectors pseudo-classes and properties which aren’t available to all browsers (IE6 is going to be your enemy most of the time) Class names should NOT BE CHAINED. IE6 does not support this: “div.classnameA.classnameB {” Check changes in all browsers as you make the changes — not once you’re 90% “done” 11
  • 12. CSS - The Cascade Sorts by origin and importance 1. inline style -> 2. embedded stylesheet -> 3. linked stylesheet A style rule with higher importance wins over identical rules with lower importance Sorts by specificity of the CSS selector Notes: If 2 or more rules have the same importance, origin and specificity, the last one wins The browsers default style sheet is treated as if it’s an imported stylesheet imported before all other 12
  • 13. Use a reset stylesheet All browsers have a default stylesheet Resets default view behaviors of many HTML elements to display uniformly across all browsers Include as first external stylesheet Example: Popular reset stylesheets Eric Meyer’s reset.css YUI reset.css 13
  • 14. CSS - File structure Choose a file structure that makes sense for your project! Some larger projects benefits from a more separated approach: reset.css typography.css layout.css gui.css Other projects may be fine using one single stylesheet 14
  • 15. CSS - ID your body Flexibility to apply page specific styles without adding separate stylesheets </head> <body id=”contactPage”> Override default style using the body ID: a { color: blue; } #contactPage a { color: red; } 15
  • 16. CSS - Sliding Doors Create dynamic length graphics for buttons, tabs and menu items Use 2 nested elements and slide background images over each other <a href=”#”><span>Text</span></a> <span> <a> left side Text right side 16
  • 17. CSS image sprites Contain several different graphics in one file WHY? Reduces number of HTTP calls to server No “flicker” when first rolling over item with hover state. Modifying CSS background-position is instant! Example: button sprites 17
  • 18. Tips when using image sprites Expect sprites to grow—group/space items accordingly Place sprites on even multiples (50px, 100px, 500px) Avoid using string values for positioning (ie, “top”, “left”, “right”, etc.). Pixels are preferred when specifying the background position for all sprites Except in the case of the sliding-doors technique. Here, a value of 100% is necessary. 18
  • 19. Tips when using image sprites If using the ‘background: ...’ CSS shorthand, enter ALL values in their PROPER order: 1. background-color: transparent | color 2. background-image: none | url(path/to/image.jpg) 3. background-repeat: no-repeat | repeat | repeat-x | repeat-y 4. background-attachment: scroll | fixed 5. background-position: 0px 0px Example: background: transparent url(../assets/sprite_main.png) no- repeat scroll 0px -50px; 19
  • 20. Tips when using image sprites Keep PSDs of the sprites up-to-date Remember that global light settings get reset to the default of 120°— double check the drop shadows with the original design, most designers prefer to use 90°!!! GIFs and PNGs optimize horizontally Experiment with compression settings. Often times, PNG-8 will be smaller. 20
  • 21. PNG optimization PNG was developed as an open-source replacement for GIF Introduced new features for compression Photoshop don’t offer any optimization options PNG-24 Truecolor PNG-8 Indexed-color PNG’s are not “unoptimizable”! 21
  • 22. GIF compression Each number represents a unique color GIF compress horizontally, thus an image like this will not compress well: 22
  • 23. PNG Scanline filtering (delta filters) 2 represents applied filter “UP” “For the current pixel take the value of the above pixel and add it to the current value.” 23
  • 24. PNG Scanline filtering (delta filters) 1 represents applied filter “SUB” “Take the value of the left pixel and add it to the current value.” 24
  • 25. PNG Scanline filtering (delta filters) 1 represents applied filter “SUB” “Take the value of the left pixel and add it to the current value.” 25
  • 26. PNG optimization Compression utilities can help us: Pick up best image type (truecolor, indexed-color) Pick up best delta filters (5 delta filters to select from) Pick up best compression strategy All these operations does NOT affect image quality! One of the best compression services: http://www.gracepointafterfive.com/punypng But where is the command line script? 26
  • 27. Progressive Enhancement The web was using Graceful Degradation Target most advanced browsers, apply fixes to older browsers Moving towards Progressive Enhancement Focus on the content! 1. Begin with semantic markup 2. Apply basic style using CSS 3. Transform into richer user experience using JS and CSS Examples: Atari.com Alkoholprofilen.se 27
  • 28. Javascript namespaces Stay away from the global namespace to avoid collisions with 3rd party code Wrap all functions in a namespace object: var myNamespace = {}; myNamespace.myFunction = function () { // I’m not a global function and I like it }; Example: Atari.com global.js 28
  • 29. jQuery - Sizzle selectors jQuery includes the Sizzle CSS selector engine from version 1.3 The syntax goes something like this: $(String selector, DOMElement context); Example: var myList = $(‘#myList’); $(‘li’, myList); Supports CSS3 selectors 29
  • 30. jQuery - Chain selectors Requires 3 DOM traversals: $(‘#mydiv’).html(‘Hello World!’); $(‘#mydiv’).css(‘border’, ‘1px solid black’); $(‘#mydiv’).fadeIn(‘fast’); Requires 1 DOM traversal: $(‘#mydiv’).html(‘Hello World!’).css(‘color’, ‘red’).fadeIn(‘fast’); OR var myDiv = $(‘#mydiv’); myDiv.html(‘Hello World!’); myDiv.css(‘color’, ‘red’); myDiv.fadeIn(‘fast’); 30
  • 31. jQuery - Chain selectors Not visually stunning! But... ... cuts down on DOM traversal and hundreds of internal calls: $(‘#mydiv’) .html(‘Hello World!’) .children(‘p’) .css(‘color’, ‘red’) .end() .css(‘background-color’, ‘#ffdead’); This chain will dip into its children, and the end() method will end the chain, reverting to the initial selector 31
  • 32. jQuery - Plugin Pattern jQuery offers a mechanism to extend it with plugins Most internal methods and functions are written using this pattern Helps us build reusable components Should be easy to override default properties 32
  • 33. jQuery - Plugin Pattern All new methods are attached to the jQuery.fn object, all functions to the jQuery object. inside methods, 'this' is a reference to the current jQuery object. Any methods or functions you attach must have a semicolon (;) at the end or compressed code will break Your method must return the jQuery object You should use this.each to iterate over the current set of matched elements Always attach the plugin to jQuery directly instead of $, so users can use a custom alias via noConflict(). 33
  • 34. Example plugin pattern Template example: The Fi plugin pattern Real world example: The Fi checkbox plugin 34
  • 35. Page specific Javascript Inline script Dynamic config vars that may change for each page load External scripts page-specific javascript file Used to load plugins Override plugin defaults with config variables EXAMPLE: load and configure labelinput plugin 35
  • 36. Qunit Latest version does not rely on jQuery Example: checkbox plugin unit test Testswarm.com 36
  • 37. JS logging alert() console.log() Blackbird JS http://www.gscottolson.com/blackbirdjs/ Example: Creating an abstract jQuery log function to wrap any logger utility. 37
  • 38. Optimize page load Use external resources not inline JS/CSS External files will be cached and minimizes document size CSS at the top JS at the bottom 38
  • 39. Javascript files always block! Blocks render because they might document.write() Downloads sequentially 39
  • 40. Skip document.ready() Will only fire once all external resources has been loaded. External scripts from third parties like Google Analytics cause long delays (~1s) before event fires Put script in correct order at bottom of page Put analytics code last! WARNING! Requires a solid file structure 40
  • 41. Example - Load order <head> reset.css layout.css </head> <body> <!-- document markup --> jquery.js jquery.checkbox.js global.js page-home.js google-analytics.js </body> 41
  • 42. Optimize load time Compress external resources! CSS compressor (YUICompressor, CSSTidy) JS compressor (JSmin, YUICompressor, etc) GZIP server response Example: YUICompressor and GZIP size comparisons 42
  • 43. JSLint Your Code What’s JSLint? Looks for problems in Javascript code It’s a code quality tool A Javascript syntax checker and validator Prevents errors occurring from compressing files! Looks at style conventions and structural problems that may cause problems WARNING: JSLint will hurt your feelings! 43
  • 44. JSLint Recommended options 1. In the “Options” box, click “The Good Parts” 2. Uncheck “Allow one var statement per function” 3. Check “Assume a browser” 4. Uncheck “Disallow ++ and --” 5. Uncheck “Require ‘use strict;’” (ECMAScript 5 strict mode) unless you actually test in a strict browser http://www.jslint.com EXAMPLE: JSlint Checbox plugin 44
  • 45. Reduce number of HTTP requests Biggest impact on end-user response times is the number of page components With an empty cache, each external component requires a new HTTP request Can’t the browser download all files in parallel? HTML/1.1 spec. suggests max 2 simultaneous downloads per hostname 45
  • 46. How do we reduce number of HTTP requests? Merge common files Global Javascript files Global stylesheets Use CSS image sprites! 46
  • 47. Automated build script Let the ANT do the work! (or any other build tool) 1. merge common files 2. compress merged files EXAMPLE: Ant build script 47
  • 48. Maximize parallel downloads Most browsers only download 2 files from same domain in parallel 2-4 domains give optimal performance Remember: Javascripts are usually downloaded and parsed sequentially EXAMPLE: Panamera Family Tree - 1 vs 4 domains 48
  • 49. Maximize parallel downloads Downloading 2 components in parallel using 1 hostname 49
  • 50. Maximize parallel downloads Downloading 8 components in parallel using 4 hostnames 50
  • 52. Maximize parallel downloads Yahoo! performance guidelines: Use at least 2 hostnames Use no more than 4 hostnames Reduce number of components in page 2-4 domains give optimal performance - test! Remember: Javascripts are usually downloaded and parsed sequentially EXAMPLE: Panamera Family Tree - 1 vs 4 domains 52
  • 53. Visual optimizations Progressive Enhancement + scripts at bottom can cause load flickering Example: Throttle checkbox plugin How do we prevent this? Hide using CSS until Javascript shows the enhanced component? Example: Test checkbox using disabled Javascript 53
  • 54. Visual optimizations Break the rules! Let’s hide enhanced components in HEAD using Javascript. Load external stylesheet hideOnLoad.css using document.write() <script> document.write(‘<link href=”...”></link>’); </script> 54
  • 55. Cache busting Add version numbers on external resources: Stylesheets Javascript files CSS sprites Images Example: <script src=”jquery.fi.checkbox.js?v=1.0” type=”...”></script> 55
  • 56. Firefox Plugins Firebug plugin & Firebug lite Web Developer toolbar HTML Validator YSlow Page Speed PixelPerfect Example: atari.com SenSEO Example: panamera.com 500k visitors since Sep10. SEO is generating 10% of visitors - most popular path after user typing in URL 56
  • 57. Tools Charles http proxy Bandwidth throttling Excellent request/response sniffing Record sessions Can parse binary AMF messages (Action Message Format) used by Adobe Flash Speed Tracer for Chrome IDE: Aptana Studio Based on Eclipse. Good support for JS frameworks! 57
  • 58. Further reading Yahoo Performance http://developer.yahoo.com/performance/ A List Apart - http://alistapart.com Sitepoint - http://sitepoint.com Smashing Magazine - http://smashingmagazine.com Ajaxian - http://ajaxian.com/ John Resig’s Blog - http://ejohn.com Steve Souder’s Blog - http://stevesouders.com 58
  • 59. Thanks! C Contact: david.lindkvist@f-i.com www.f-i.com 59

Editor's Notes